package com.example.demo.practice.ui;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.demo.practice.R;

public class ImageIcon extends LinearLayout {
    public ImageIcon(Context context, AttributeSet attrs) {
        super(context, attrs);
        setOrientation(VERTICAL);
        setGravity(Gravity.CENTER_HORIZONTAL);
        //获取属性
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ImageIcon);
        String title = typedArray.getString(R.styleable.ImageIcon_title_text);
        int text_color = typedArray.getInt(R.styleable.ImageIcon_text_color, 0);
        float text_size = typedArray.getDimension(R.styleable.ImageIcon_title_size, 0);
        Drawable icon = typedArray.getDrawable(R.styleable.ImageIcon_icon_pic);
        int icon_size = typedArray.getDimensionPixelSize(R.styleable.ImageIcon_icon_size,0);

        //实例化控件
        ImageView imageView = new ImageView(context);
        TextView textView = new TextView(context);
        imageView.setImageDrawable(icon);

        textView.setText(title);
        textView.setTextColor(text_color);
        textView.setTextSize(text_size);

        //添加控件，设置大小
        addView(imageView);
        addView(textView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        ViewGroup.LayoutParams layoutParams = imageView.getLayoutParams();
        layoutParams.width=icon_size;
        layoutParams.height=icon_size;

        typedArray.recycle();
    }
}
